﻿using Microsoft.EntityFrameworkCore;
using System.Reflection;
using NLog.Web;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using ServiceManagement.Consul;
using B.S.Databasic.Api.Read.AllError;
using B.S.Databasic.Api.Read.Common;
using B.S.Databasic.Api.Read.Profiles;
using B.S.Databasic.Infrastructure;
using B.S.Databasic.Infrastructure.Interface;
using B.S.Databasic.Infrastructure.Inpement;

namespace B.S.Databasic.Api.Read.Extensions
{
    /// <summary>
    /// 扩展方法 静态类 静态方法 this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.);
            //注册全局异常处理
            builder.Services.AddControllers(x => x.Filters.Add<GloabIExcptionfilter>());
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.Databasic.Api.Read.xml", true));
            //注册上下文 开发环境下启用SQL日志记录
            builder.Services.AddDbContext<MyDbContext>(x =>
            {
                x.UseMySql(builder.Configuration.GetConnectionString("db"), new MySqlServerVersion("5.7"));
            });
            //注册http获取请求上下文
            builder.Services.AddHttpContextAccessor();
            builder.Services.AddScoped<IIdentivyService, IdentivyService>();
            //JWT
            var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SigningKey);
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtSettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtSettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
            // 配置Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[]
                        {

                        }
                    }
                });
            });
            //注册consul
            builder.Configuration.Register();
            //注册中介者
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //配置Base模块
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //配置AutoMapper
            builder.Services.AddAutoMapper(typeof(RoleProfile));
            //配置日志
            builder.Host.UseNLog();

            return builder;
        }

        //public static IServiceCollection AddDBContextAccessor<T>(this IServiceCollection services, string connectionString, bool enableSqlLog) where T : DbContext
        //{
        //    return services.AddDbContext<MyDbContext>(x =>
        //    {
        //        x.UseSqlServer(connectionString, action =>
        //        {
        //            action.EnableRetryOnFailure(
        //                maxRetryCount: 10,//最大重试次数
        //                maxRetryDelay: TimeSpan.FromSeconds(60),//每次重试间隔时间 最大延迟
        //                errorNumbersToAdd: null //添加需要重试的错误代码,null表示使用默认错误代码
        //            );
        //        })
        //        .EnableSensitiveDataLogging();//启用敏感数据日志记录，便于调试,但在生产环境中应谨慎使用避免泄露敏感信息
        //        if (enableSqlLog)
        //        {
        //            x.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddFilter(
        //            category: DbLoggerCategory.Database.Name, //类别
        //            level: LogLevel.Information //日志级别
        //            ).AddConsole())); //控制台日志
        //        }
        //    });
        //}

    }
}
